package access.spg.android.com.accessibilitytest;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import java.util.List;
import java.util.Random;

@RequiresApi(api = Build.VERSION_CODES.O)
public class DFTTService extends AccessibilityService {
    private static String tag="DFTT";

    private static String ITEM_ID="com.songheng.eastnews:id/t8";
    private static String ARTICLE_MORE="com.songheng.eastnews:id/a4y";

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(tag,"onServiceConnected");
//        AccessibilityServiceInfo info=new AccessibilityServiceInfo();
//        info.packageNames=new String[]{"com.jifen.qukan"};
//        setServiceInfo(info);
//        searchNode();
    }

    @Override
    public void onInterrupt() {
        Log.d(tag,"onInterrupt");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(tag,"onUnbind");
        return super.onUnbind(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        switch (event.getEventType())
        {
            case AccessibilityEvent.TYPE_VIEW_SCROLLED:
//                scrollUp(false,-1);
                break;
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                try
                {
                    if(event.getText().get(0).equals("财经"))
                    {
                        readNews();
                    }
                }catch (Exception e){

                }
                break;
        }
    }


    private void readNews()
    {
        Log.e(tag, "============开始readNews===============" );

        for(int i=0;i<=2;i++)
        {
            scrollUp();
        }

        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        List<AccessibilityNodeInfo> list=rootNode.findAccessibilityNodeInfosByViewId(ITEM_ID);
        if(list==null || list.size()==0)
        {
            Log.e(tag, "============没有相关id===============" );
        }else
        {
            Log.e(tag, "本页新闻数量"+list.size() );
        }
        int length=list.size();
        if(list.size()>1)
            length--;
        for(int i=0;i<length;i++)
        {
            try
            {
                AccessibilityNodeInfo node=list.get(i);
                if(onClickByNodeLocation(node))
                {
                    Log.e(tag, "============进入详情===============" );
                    readNewsDetail();
                    Log.e(tag, "============返回列表===============" );
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                }else
                {
                    Thread.sleep(500);
                }

            }catch (Exception e){}
        }
        readNews();

    }


    private boolean onClickByNodeLocation(AccessibilityNodeInfo node)
    {
        if(node==null)
        {
            Log.e(tag, "============元素为空，无法点击===============" );
            return false;
        }

        Rect rect=new Rect();
        node.getBoundsInScreen(rect);
        int y=rect.top+20;
        int x=rect.left+20;
        Log.e(tag, "x=="+x );
        Log.e(tag, "y=="+y );
        Path path = new Path();
        path.moveTo(x, y);
        path.lineTo(x, y);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 500L, 800L,false))
                .build();

        dispatchGesture(gestureDescription, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.e(tag, "============List onCompleted===============" );
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(tag, "============List onCancelled===============");
            }
        }, new Handler(Looper.getMainLooper()));

        return true;
    }

    private void readNewsDetail()
    {
        Random ra =new Random();

        for(int i=0;i<3;i++)
        {
            try
            {
                int tmp=ra.nextInt(2)+5;
                Thread.sleep(tmp*1000);
            }catch (Exception e){}
            scrollUp();
        }
        Log.e(tag, "============检查阅读全文标志===============" );
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        List<AccessibilityNodeInfo> list=rootNode.findAccessibilityNodeInfosByViewId(ARTICLE_MORE);
        if(list!=null && list.size()>0)
        {
            AccessibilityNodeInfo node=list.get(0);
            onClickByNodeLocation(node);
            try
            {
                Thread.sleep(800);
            }catch (Exception e){}
        }

        for(int i=0;i<2;i++)
        {
            scrollUp();
            try
            {
                int tmp=ra.nextInt(2)+5;
                Thread.sleep(tmp*1000);
            }catch (Exception e){}
        }

    }




    /**
     * 向上翻页
     *
     * */
    private void scrollUp()
    {

            GestureDescription.Builder builder = new GestureDescription.Builder();
             Path path = new Path();
             float y1 = MyUtil.getWindowHeight(this)*0.8f;
             float y2 = MyUtil.getWindowHeight(this)*0.1f;
             float x =MyUtil.getWindowWidth(this)/2f;
             path.moveTo(x, y1);
             path.lineTo(x, y2);
             GestureDescription gestureDescription = builder
                .addStroke(new GestureDescription.StrokeDescription(path, 200L, 800L,false))
                .build();

             dispatchGesture(gestureDescription, new GestureResultCallback() {
                 @Override
                 public void onCompleted(GestureDescription gestureDescription) {
                     super.onCompleted(gestureDescription);
                     Log.e(tag, "============Swipe onCompleted===============" );
                 }

                 @Override
                 public void onCancelled(GestureDescription gestureDescription) {
                     super.onCancelled(gestureDescription);
                     Log.e(tag, "============Swipe onCancelled===============");
                 }
             }, new Handler(Looper.getMainLooper()));

     }








}
